package com.innotek.testworkstation.util;

import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName BuiltFunctionUtils
 * @Description 内置方法类，用于给测试用例调用
 * @Author wangx
 * @Date 2021/7/15 下午6:16
 * @Version 1.0
 **/

@Slf4j
public class BuiltFunctionUtils {

    private static ThreadLocal<Random> random = new ThreadLocal() {
        @Override
        protected Random initialValue() {
            return new Random();
        }

    };

    /**
     * 生成随机字符串(数字和大小写字母混合)
     * @param length 字符串长度
     * @return 返回字符串
     */
    public static String getStringRandom(int length) {

        StringBuilder val = new StringBuilder();

        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.get().nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.get().nextInt(2) % 2 == 0 ? 65 : 97;
                val.append((char) (random.get().nextInt(26) + temp));
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val.append(random.get().nextInt(10));
            }
        }
        return val.toString();
    }

    /**
     * 生成随机字符串(数字和大写字母混合)
     * @param length 字符串长度
     * @return 返回字符串
     */
    public static String getStringRandomToUpperCase(int length){
        return getStringRandom(length).toUpperCase();
    }


    /**
     * 获取时间（按传入的格式，格式化时间）
     * @param format 格式
     * @return
     */
    public static String nowTime(String format){
        String datetime = null;
        if(format.length()==0){
            datetime = Long.toString(System.currentTimeMillis());
        }else {
            try {
                SimpleDateFormat df = new SimpleDateFormat(format);
                datetime = df.format(new Date());
            }catch (IllegalStateException e){
                log.error("format参数格式有误：{}", format, e);
            }

        }
        return datetime;
    }

    /**
     * 获取当前时间戳
     * @return 时间戳
     */
    public static String nowTime(){
        return nowTime("");
    }

    /**
     *
     * @param format 时间格式化
     * @param shift 时间加减规则
     *              例子可见：https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-
     *              Examples:
     *              "PT20.345S" -- parses as "20.345 seconds"
     *              "PT15M"     -- parses as "15 minutes" (where a minute is 60 seconds)
     *              "PT10H"     -- parses as "10 hours" (where an hour is 3600 seconds)
     *              "P2D"       -- parses as "2 days" (where a day is 24 hours or 86400 seconds)
     *              "P2DT3H4M"  -- parses as "2 days, 3 hours and 4 minutes"
     *              "P-6H3M"    -- parses as "-6 hours and +3 minutes"
     *              "-P6H3M"    -- parses as "-6 hours and -3 minutes"
     *              "-P-6H+3M"  -- parses as "+6 hours and -3 minutes"
     * @return
     */
    public static String timeShift(String format, String shift){
        // 获取系统默认时区的当前时间
        ZonedDateTime zonedDateTimeToShift = ZonedDateTime.now(ZoneId.systemDefault());
        DateTimeFormatter formatter = null;
        if(!StringUtils.isEmpty(format)){
            try {
                // 格式化时间
                formatter = DateTimeFormatter.ofPattern(format);
            }catch (IllegalArgumentException ex){
                log.error("格式化错误，'{}'规则有误", format,ex);
            }

        }
        if (!StringUtils.isEmpty(shift)) {
            try {
                // 时间格式解析
                Duration duration = Duration.parse(shift);
                // 返回加减后的时间
                zonedDateTimeToShift = zonedDateTimeToShift.plus(duration);
            } catch (DateTimeParseException ex) {
                log.error(
                        "时间加减格式错误： '{}'  "
                                + "(具体规则可见文档 https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html#parse-java.lang.CharSequence-) ",
                        shift, ex);
            }
        }
        String dateString;
        if (formatter != null) {
            dateString = zonedDateTimeToShift.format(formatter);
        } else {
            dateString = String.valueOf(zonedDateTimeToShift.toInstant().toEpochMilli());
        }
        return dateString;
    }

    /**
     * 字符串转INT类型
     */
    public static int stringToInt(String value) {
        try {
            return Integer.parseInt(value);
        } catch (Exception e) {
            log.error("String 转换 int 出错！", e);
            return -1;
        }
    }

    /**
     * 产生一个 范围内的数字
     * @param start  最小值
     * @param end  最大值
     * @return 随机数
     */
    public static Integer getRandomRange(int start, int end){
        return getRandomInt(end - start) + start;
    }


    /**
     * 获取随机数，获取1~num 的数字，包含 num
     *
     * @param num 随机数上限
     * @return 随机数
     */
    public static int getRandomInt(int num) {
        return random.get().nextInt(num) + 1;
    }

    /**
     * 等待
     * @param s 秒
     */
    public static void sleep(int s){
        try {
            Thread.sleep(s*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
